package com.codingxyz.simple.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 李新飘
 * @version 1.0.0
 * @since JKD 1.8
 */
public class AnnotationTest {


    public static void main(String[] args) throws NoSuchFieldException, SecurityException {



        AnnotationTest c = new AnnotationTest();

// 获取方法上的注解值

        //c.getMethodAnnotationValue();

// 获取字段上的注解值

       // c.getFieldAnnotationValue();

        TestClass testClass = new TestClass();
        testClass.setName("我的名字");
        testClass.setMyFiled("我的字段");

        try {
            c.getObjectAnnotation(testClass);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void getObjectAnnotation(TestClass testClass) throws Exception{


        Field[] fields = testClass.getClass().getDeclaredFields();

        for (Field f : fields) {
            // 判断字段注解是否存在
            boolean annotationPresent2 = f.isAnnotationPresent(FieldInterface.class);

            if (annotationPresent2) {

                FieldInterface name = f.getAnnotation(FieldInterface.class);
                // 获取注解值
                String nameStr = name.name();

                f.setAccessible(true);
                System.out.println(" annotation name: "+nameStr);
                System.out.println(" filed :: "+f.get(testClass));
            }

        }
    }



    public void getMethodAnnotationValue() {
        // 获取所有的方法
        Method[] name = TestClass.class.getDeclaredMethods();

        for (Method str : name) {
            // 判断是否方法上存在注解
            boolean annotationPresent = str.isAnnotationPresent(MethodInterface.class);

            if (annotationPresent) {
                // 获取自定义注解对象
                MethodInterface methodAnno = str.getAnnotation(MethodInterface.class);

                // 根据对象获取注解值
                String isNotNullStr = methodAnno.name();

                System.out.println(isNotNullStr);

            }

        }
    }

    public void getFieldAnnotationValue() throws NoSuchFieldException, SecurityException {
        // 获取所有的字段
        Field[] fields = TestClass.class.getDeclaredFields();

        for (Field f : fields) {
            // 判断字段注解是否存在
            boolean annotationPresent2 = f.isAnnotationPresent(FieldInterface.class);

            if (annotationPresent2) {

                FieldInterface name = f.getAnnotation(FieldInterface.class);
                // 获取注解值
                String nameStr = name.name();

                System.out.println(nameStr);
            }

        }
    }


}
